/*
 * DevManager.cpp
 *
 *  Created on: 2017-10-1
 *      Author: hxh
 */

#include "DevManager.h"

#include <iostream>
#include "Parse.h"



DevManager::DevManager() {

}

DevManager::~DevManager() {

}

/**
 * 将device添加到list中
 */
bool DevManager::update(Device *dev) {

	m_devices[dev->getHid()] = dev;
	m_fd2hid[dev->getSock()] = dev->getHid();
	return true;
}

string DevManager::getlist() {
	//全部设备和设备状态。
	return Parse::map2jsonstr(m_devices);
}

Device* DevManager::getdevice(string hid) {
	device_iter = m_devices.find(hid);
	if(device_iter != m_devices.end())
	{
		return device_iter->second;
	}
	return NULL;
}

//用fd删除设备，fd找到hid，再用hid删除设备
bool DevManager::removeDevice(int fd) {
	string hid;
	if( m_fd2hid.find(fd) != m_fd2hid.end())
	{
		hid = m_fd2hid[fd];

		if(m_devices.find(hid) != m_devices.end())
		{
			m_devices.erase(hid);
			cout<<"delete "<< hid << fd<< "in m_devices successful"<<endl;
			return true;
		}

		m_fd2hid.erase(fd);
		cout<<"delete "<< hid << "_"<<fd<< " in m_fd2hid successful"<<endl;
	}
	return false;
}

bool DevManager::removeDevice(string hid) {
	if(m_devices.find(hid) != m_devices.end())
	{
		m_devices.erase(hid);
		cout<<"delete "<< hid << " in m_devices successful"<<endl;
		return true;
	}
	return false;
}
